//
//  ZCCommentVC.m
//  zctx
//
//  Created by apple on 15/12/30.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "ZCCommentVC.h"
#import "ZCInvolvedcommentsCell.h"
#import "HcCustomKeyboard.h"
#import "ZCCommentDetailsVC.h"
#import "ZCLoginVC.h"
@interface ZCCommentVC ()<UITableViewDataSource,UITableViewDelegate,ZCInvolvedcommentsCellDelegate,UITextFieldDelegate,HcCustomKeyboardDelegate>
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)UITextField *mTextView;

@property (nonatomic,assign)NSInteger offset;

@property (nonatomic,strong)UILabel *alertLable;
@property  BOOL isremove;
@end

@implementation ZCCommentVC

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCCommentVC"];
    [MTA trackPageViewBegin:@"ZCCommentVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCCommentDetailsVC"];
    [MTA trackPageViewEnd:@"ZCCommentDetailsVC"];
    self.tabBarController.hidesBottomBarWhenPushed = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initnavegation];
    self.navigationItem.title = @"评论";
    self.isremove = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    self.dataArray = [[NSMutableArray alloc]init];
    _offset = 0;
    

    [self initTableView]; //初始化UITableView
    [self initFooterView];
    [self requestData];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCInvolvedcommentsCell" bundle:nil] forCellReuseIdentifier:@"commemtsCell"];
    self.tableView.mj_footer = [MJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    [self.view addSubview:self.alertLable];
    [self.alertLable makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX).with.offset(0);
        make.centerY.equalTo(self.view.centerY).with.offset(0);
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(21);
    }];
    self.alertLable.hidden = YES;
    
    //个人信息请求
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [self requestData];
//    });
}
-(void)requestData{
    if (_offset==0) {
        [GMDCircleLoader setOnView:self.view withTitle:@"努力加载中..." animated:YES];
    }
    if (self.isarticle ==1) {
        NSString *ctype = nil;
        if ([self.isweekly isEqualToString:@"1"]) {
            ctype = @"6";
        }else{
            ctype = @"0";
        }
        [NetworkManager requestIndexGetAddarticleCommentslikeWithNewscid:self.pid mid:UserModel.mid password:UserModel.password pagecount:[NSString stringWithFormat:@"%ld",(long)_offset] pid:@"0" ctype:ctype success:^(NSDictionary *dictResponse) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
            [self.tableView.mj_footer endRefreshing];
            NSObject *dict =(NSObject *)[dictResponse objectForKey:@"content"];
            if ([dict isKindOfClass:[NSArray class]]) {
                NSArray *array  = (NSArray *)dict;
                if (array.count>0) {
                    
                    NSLog(@"sdfas");
                    self.alertLable.hidden = YES;
                    self.tableView.hidden = NO;
                    for (NSDictionary *dict in array) {
                        ZCInvolvedDetailsModelHotComments *model = [ZCInvolvedDetailsModelHotComments modelObjectWithDictionary:dict];
                        [self.dataArray addObject:model];
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
                }else{
                    if (_offset==0) {
                        self.alertLable.hidden = NO;
                        self.tableView.hidden = YES;
                    }
                }
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
                if (_offset==0) {
                    self.alertLable.hidden = NO;
                    self.tableView.hidden = YES;
                }
            }
        } failure:^(NSError *error) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
        }];
    }else{
        
        NSLog(@"项目的更多评论");
        [NetworkManager requestFoundingGetOnecommentsWithId:self.pid Mid:UserModel.mid password:UserModel.password pagecount:[NSString stringWithFormat:@"%ld",(long)_offset] pid:@"0" success:^(NSDictionary *dictResponse) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
            [self.tableView.mj_footer endRefreshing];
            NSObject *dict =(NSObject *)[dictResponse objectForKey:@"content"];
            if ([dict isKindOfClass:[NSArray class]]) {
                NSArray *array  = (NSArray *)dict;
                if (array.count>0) {
                    NSLog(@"121213124");
                    for (NSDictionary *dict in array) {
                        ZCInvolvedDetailsModelHotComments *model = [ZCInvolvedDetailsModelHotComments modelObjectWithDictionary:dict];
                        [self.dataArray addObject:model];
                    }
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self.tableView reloadData];
                    });
                }
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } failure:^(NSError *error) {
            [GMDCircleLoader hideFromView:self.view animated:YES];
        }];
    }
}
#pragma mark 加载更多
-(void)loadMoreData{
    //上拉加载
    _offset = _offset+1;
    [self requestData];
}

-(void)initFooterView{
    UIView *footer = [[UIView alloc]init];
    footer.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:footer];
    [footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.bottom).with.offset(0);
        make.height.mas_equalTo(@(60));
        make.right.equalTo(self.view.right).with.offset(0);
        make.left.equalTo(self.view.left).with.offset(0);
    }];
    self.mTextView =[[UITextField alloc]init];
    [footer addSubview:self.mTextView];
    [self.mTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(footer.centerY);
        make.height.mas_equalTo(@(30));
        make.right.equalTo(footer.right).with.offset(-10);
        make.left.equalTo(footer.left).with.offset(10);
    }];
    self.mTextView.backgroundColor =[UIColor whiteColor];
    self.mTextView.delegate = self;
    self.mTextView.placeholder = @"我来说两句";
    self.mTextView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    self.mTextView.layer.cornerRadius = 5;
    self.mTextView.layer.borderWidth = 1;
    self.mTextView.layer.borderColor = [UIColor colorWithRed:210.0/255.0 green:210.0/255.0 blue:210.0/255.0 alpha:1].CGColor;
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}

-(void)backButtonPressed{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.sectionFooterHeight = 0.0001;
    self.tableView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
    self.tableView.separatorColor = RGB(236, 237, 238);
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0,60, 0));
    }];
}

#pragma mark UITableViewDataSource,UITableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSLog(@"count = %ld",self.dataArray.count);
    
    if (self.dataArray.count>0) {
        return self.dataArray.count;
    }else{
        return 0;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *IDcell = @"commemtsCell";
    ZCInvolvedcommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:IDcell];
    if (!cell) {
        cell = [[ZCInvolvedcommentsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:IDcell];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        cell.model =self.dataArray[indexPath.row];
        cell.indexPach = indexPath;
        cell.delegate = self;
    });
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *reuseIdentifier = @"commemtsCell";
    ZCInvolvedcommentsCell *cell = [self.tableView dequeueReusableCellWithIdentifier:  reuseIdentifier];
    ZCInvolvedDetailsModelHotComments *model =self.dataArray[indexPath.row];
    [cell.contentLable setText:model.content];
    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];
    // 得到cell的contentView需要的真实高度
    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    // 要为cell的分割线加上额外的1pt高度。因为分隔线是被加在cell底边和contentView底边之间的。
    height +=1.0f;
    return height;

}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0.000001;
    }else{
        return 10;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self performSelector:@selector(unselectCell:) withObject:nil afterDelay:0.3];
    [self commentButtonClickindex:indexPath];
}


-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, 10)];
    return headView;
}

-(void)unselectCell:(id)sender{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}


-(void)likeButtonClickindex:(NSIndexPath *)indexPath islogin:(BOOL)login{
    
    if (login == YES) {
        ZCInvolvedDetailsModelHotComments *model =self.dataArray[indexPath.row];
        
        if (self.isarticle == 1) {
            [NetworkManager requestIndexGetAddarticleCommentlikeWithNewscid:model.hotCommentsIdentifier mid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
                
            } failure:^(NSError *error) {
            }];
        }else{
            [NetworkManager requestFoundingGetOnecommentlikeWithCId:model.hotCommentsIdentifier Mid:UserModel.mid password:UserModel.password success:^(NSDictionary *dictResponse) {
                
            } failure:^(NSError *error) {
                
            }];
        }
    }else{
        [self gotoLogin];
    }
}
-(void)commentButtonClickindex:(NSIndexPath *)indexPath{
    ZCCommentDetailsVC *zcmment = [[ZCCommentDetailsVC alloc]init];
    zcmment.comments =self.dataArray[indexPath.row];
    zcmment.pid = self.pid;
    zcmment.isarticles = self.isarticle;
    zcmment.isweekly = self.isweekly;
    NSLog(@"isarticle = %ld",self.isarticle);
    zcmment.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:zcmment animated:YES];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    NSLog(@"sdfa");
    
    if (UserModel.password.length>1) {
        [[HcCustomKeyboard customKeyboard]textViewShowView:self customKeyboardDelegate:self andType:HcCustomKeyboardTypeTextfield andplaceholder:@"我来说两句"];
    }else{
        [textField resignFirstResponder];
        ZCLoginVC *loginVC = [[ZCLoginVC alloc]init];
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}
-(void)talkBtnClick:(UITextView *)textViewGet
{
    NSLog(@"%@",textViewGet.text);
    if (self.isarticle ==1) {
        
        NSString *ctype = nil;
        if ([self.isweekly isEqualToString:@"1"]) {
            ctype = @"6";
        }else{
            ctype = @"0";
        }
        [NetworkManager requestIndexGetAddarticleWithNewsid:self.pid mid:UserModel.mid password:UserModel.password content:textViewGet.text  pid:@"0" ctype:ctype success:^(NSDictionary *dictResponse) {
            NSString *err = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"err"]];
            NSString *content =[NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"content"]];
            if ([err isEqualToString:@"0"]) {
                [[[iToast makeText:@"评论成功"]setGravity:iToastGravityCenter] show];
                ZCInvolvedDetailsModelHotComments *hotcom = [[ZCInvolvedDetailsModelHotComments alloc]init];
                hotcom.avatar = UserModel.avatar;
                hotcom.ctime =[NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];;
                hotcom.content = textViewGet.text;
                hotcom.likecount = @"0";
                hotcom.commentCount = @"0";
                hotcom.username = UserModel.username;
                hotcom.hotCommentsIdentifier = content;
                hotcom.forId = self.pid;
                hotcom.pid =content;
                hotcom.ctype = @"1";
                [self.dataArray insertObject:hotcom atIndex:0];
                self.isremove = YES;
                self.tableView.hidden = NO;
                self.alertLable.hidden = YES;
                [self.tableView reloadData];
            }else{
                [[[iToast makeText:@"评论失败"]setGravity:iToastGravityCenter] show];
            }

        } failure:^(NSError *error) {
            
        }];
    }else{
        NSLog(@"xiam------");
        [NetworkManager requestFoundingGetOnecommentWithId:self.pid Mid:UserModel.mid password:UserModel.password content:textViewGet.text pid:@"0" success:^(NSDictionary *dictResponse) {
            NSString *err = [NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"err"]];
            
            NSString *content =[NSString stringWithFormat:@"%@",[dictResponse objectForKey:@"content"]];
            if ([err isEqualToString:@"0"]) {
                [[[iToast makeText:@"评论成功"]setGravity:iToastGravityCenter] show];
                
                ZCInvolvedDetailsModelHotComments *hotcom = [[ZCInvolvedDetailsModelHotComments alloc]init];
                hotcom.avatar = UserModel.avatar;
                hotcom.ctime =[NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];;
                hotcom.content = textViewGet.text;
                hotcom.likecount = @"0";
                hotcom.commentCount = @"0";
                hotcom.username = UserModel.username;
                hotcom.hotCommentsIdentifier = content;
                hotcom.forId = self.pid;
                hotcom.pid =content;
                hotcom.ctype = @"1";
                [self.dataArray insertObject:hotcom atIndex:0];
                [self.tableView reloadData];
            }else{
                [[[iToast makeText:@"评论失败"]setGravity:iToastGravityCenter] show];
            }
        } failure:^(NSError *error) {
        }];
    }
}

-(void)gotoLogin{
    ZCLoginVC *zclogin = [[ZCLoginVC alloc]init];
    zclogin.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:zclogin animated:YES];
}


-(UILabel *)alertLable{
    if (!_alertLable) {
        _alertLable = [[UILabel alloc]init];
        _alertLable.textColor = [UIColor colorWithHexString:@"#8a8a8a"];
        _alertLable.textAlignment = NSTextAlignmentCenter;
        _alertLable.font = [UIFont systemFontOfSize:15];
        _alertLable.text = @"暂无评论,我来说两句";
    }
    return _alertLable;
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
